#include <stdio.h>
#include <string.h>
#include <dbg.h>

#define MAX_LEN 100

int getLength(const char *p);
int indexof(const char *s, const char *t);

int main(int argc, char *argv[])
{
    int i;
    char s[MAX_LEN] = "hello czx";
    char t[MAX_LEN] = "hel";
    i = indexof(s, t);
    check(i == 0, "Expect 0, but was %d", i);
   
    strcpy(t, "Hell");
    i = indexof(s, t);
    check(i == -1, "Expect -1, but was %d", i);
    
    strcpy(t, "hello czx!");
    i = indexof(s, t);
    check(i == -1, "Expect -1, but was %d", i);
    
    strcpy(t, "czx");
    i = indexof(s, t);
    check(i == 6, "Expect 6, but was %d", i);

    strcpy(t, "o c");
    i = indexof(s, t);
    check(i == 4, "Expect 4, but was %d", i);

    printf("Test indexof success.\n");
    return 0;

error:
    return -1;
}

int getLength(const char *p)
{
    int counter = 0;
    if(p == NULL) return counter;

    while(p[counter] != '\0')
        ++counter;

    return counter;
}

int indexof(const char *s, const char *t)
{
    int index = -1;
    int len1, len2;
    int flag, i, j;
    len1 = getLength(s);
    len2 = getLength(t);
    if(len2 > len1) return index;

    for(i = 0; i <= len1 - len2; i++)
    {
        flag = 0;
        j = 0;
        for(j = 0; j < len2; ++j)
        {
            if(s[i + j] != t[j])
            {
                flag = -1;
                break;
            }
        }
        if(flag == 0)
        {
            index = i;
            break;
        }
    }

    return index;
}
